package com.masterclient.app.modules.shop;

import android.animation.Animator;
import android.graphics.Color;
import android.graphics.Typeface;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.airbnb.lottie.LottieAnimationView;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.load.Transformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselibrary.base.FragmentHostActivity;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselibrary.utils.TimeUtil;
import com.eoner.baselibrary.utils.Utils;
import com.eoner.baselibrary.utils.ViewTransformUtil;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.router.AroutePath;
import com.masterclient.app.BaseFragment;
import com.masterclient.app.R;
import com.masterclient.app.modules.shop.adapter.DealerToolsAdapter;
import com.masterclient.app.modules.shop.beans.DealerBean;
import com.masterclient.app.modules.shop.contract.DealerContract;
import com.masterclient.app.modules.shop.contract.DealerPresenter;
import com.masterclient.app.modules.shop.widget.DealerBenchTextView;
import com.masterclient.app.modules.shop.widget.GuideDealerBenchDialog;
import com.masterclient.app.utils.CommonUtil;
import com.masterclient.app.widget.ShareCommonDialog;
import com.eoner.uikit.header.MyRefreshHead;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;

import static com.eoner.uikit.header.MyRefreshHead.LOTTIE;


@Route(path = AroutePath.DEALER_BENCH_FRAGMENT)
public class DealerBenchFragment extends BaseFragment<DealerPresenter> implements DealerContract.View {

    @BindView(R.id.view_scroll)
    ScrollView viewScroll;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.layout_notice)
    LinearLayout layoutNotice;
    @BindView(R.id.tv_notice)
    DealerBenchTextView tvNotice;
    @BindView(R.id.tv_shop_title)
    TextView tvShopTitle;
    @BindView(R.id.iv_shop_logo)
    ImageView ivShopLogo;
    @BindView(R.id.fl_bar)
    FrameLayout flBar;
    @BindView(R.id.iv_share_dealer)
    ImageView ivShareDealer;
    @BindView(R.id.iv_share)
    LottieAnimationView ivShare;
    @BindView(R.id.iv_share_shop)
    ImageView ivShareShop;

    @BindView(R.id.tv_stay_send)
    TextView tvStaySend;
    @BindView(R.id.tv_stay_pay)
    TextView tvStayPay;
    @BindView(R.id.tv_stay_take)
    TextView tvStayTake;
    @BindView(R.id.tv_stay_sale)
    TextView tvStaySale;

    @BindView(R.id.tv_auto_order)
    TextView tvAutoOrder;
    @BindView(R.id.tv_auto_order_num)
    TextView tvAutoOrderNum;
    @BindView(R.id.tv_auto_order_unit)
    TextView tvAutoOrderUnit;
    @BindView(R.id.tv_auto_order_desc)
    TextView tvAutoOrderDesc;
    @BindView(R.id.switch_button_bg)
    View switchButtonBg;
    @BindView(R.id.switch_button_new)
    TextView switchButtonNew;
    @BindView(R.id.switch_button_classic)
    TextView switchButtonClassic;
    @BindView(R.id.recycler_tools)
    RecyclerView recyclerTools;
    @BindView(R.id.layout_dealer_head)
    LinearLayout layoutDealerHead;
    @BindView(R.id.view_to_stay_send)
    FrameLayout viewToStaySend;
    @BindView(R.id.lottie_to_stay_send)
    LottieAnimationView lottieToStaySend;
    @BindView(R.id.view_to_stay_sale)
    FrameLayout viewToStaySale;
    @BindView(R.id.lottie_to_stay_sale)
    LottieAnimationView lottieToStaySale;

    private boolean isSwitchNew = true;
    private boolean firstSwitchNew = true;


//    private DealerItemAdapter dealerItemAdapter;
    private DealerToolsAdapter toolsAdapter;
    private DealerBean dealerBean;
    private int newsPosition = 0;
    private TranslateAnimation mShowAction;

//    private final Handler mHandler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            switch (msg.what) {
//                case 1:
//                    if (tvNotice == null) return;
//                    tvNotice.setText(dealerBean.noticeAdv.get(newsPosition).title);
//                    tvNotice.setTag(newsPosition);
//                    if (dealerBean.noticeAdv.size() > 1) {
//                        tvNotice.startAnimation(mShowAction);
//                    }
//                    if (newsPosition >= dealerBean.noticeAdv.size() - 1) {
//                        newsPosition = 0;
//                    } else {
//                        newsPosition++;
//                    }
//                    mHandler.sendEmptyMessageDelayed(1, 3000);
//                    break;
//            }
//        }
//    };

    public static DealerBenchFragment newInstance() {
        return new DealerBenchFragment();
    }

    @Override
    protected View getRootView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_dealer_bench, null);
    }

    @Override
    protected void initOnlyOnce() {
        super.initOnlyOnce();
        ImmersionBar.with(this).transparentStatusBar().fitsSystemWindows(false).init();
        MyRefreshHead myRefreshHead = new MyRefreshHead(getActivity(), 1, LOTTIE);
        myRefreshHead.changeBackColor(Color.parseColor("#F9193F"));
        myRefreshHead.changeTextColor(Color.parseColor("#FFFFFF"));
        refreshLayout.setBackgroundColor(Color.parseColor("#F9193F"));
        refreshLayout.setRefreshHeader(myRefreshHead);
        mShowAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                1f, Animation.RELATIVE_TO_SELF, 0f);
        mShowAction.setDuration(500);
        flBar.setPadding(0,ImmersionBar.getStatusBarHeight(this),0,0);
        isSwitchNew = SPUtils.getInstance().getBoolean(Config.SHOW_DEALER_BENCH_GRID_NEW, true);
        firstSwitchNew = isSwitchNew;
        if (!firstSwitchNew){
            switchButtonNew.setTextColor(Color.parseColor(isSwitchNew?"#F23051":"#999faa"));
            switchButtonNew.setTypeface(Typeface.defaultFromStyle(isSwitchNew?Typeface.BOLD:Typeface.NORMAL));
            switchButtonClassic.setTextColor(Color.parseColor(isSwitchNew?"#999faa":"#F23051"));
            switchButtonClassic.setTypeface(Typeface.defaultFromStyle(isSwitchNew?Typeface.NORMAL:Typeface.BOLD));
            ((FrameLayout.LayoutParams)switchButtonBg.getLayoutParams()).setMargins(ScreenUtils.dp2px(46),0,0,0);
        }

        Utils.setDin(tvStaySend,getActivity());
        Utils.setDin(tvStayPay,getActivity());
        Utils.setDin(tvStayTake,getActivity());
        Utils.setDin(tvStaySale,getActivity());
        ivShare.playAnimation();

        toolsAdapter = new DealerToolsAdapter();
        recyclerTools.setLayoutManager(new LinearLayoutManager(getActivity()){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        toolsAdapter.bindToRecyclerView(recyclerTools);

        switchButtonBg.animate().setListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                switchButtonNew.setTextColor(Color.parseColor(isSwitchNew?"#F23051":"#999faa"));
                switchButtonNew.setTypeface(Typeface.defaultFromStyle(isSwitchNew?Typeface.BOLD:Typeface.NORMAL));
                switchButtonClassic.setTextColor(Color.parseColor(isSwitchNew?"#999faa":"#F23051"));
                switchButtonClassic.setTypeface(Typeface.defaultFromStyle(isSwitchNew?Typeface.NORMAL:Typeface.BOLD));

            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }
        });

        tvNotice.setClickLisener(new DealerBenchTextView.ItemClickLisener() {
            @Override
            public void onClick(int position) {
                CommonUtil.goAnyWhere(mContext, dealerBean.noticeAdv.get(position).redirectUrl,
                        dealerBean.noticeAdv.get(position).redirectId, "", "", "");
            }
        });

        refreshLayout.setOnRefreshListener((refreshLayout) ->{
            mPresenter.getDealerData();
        });
    }


    @Override
    public void onResume() {
        super.onResume();
        mPresenter.getDealerData();
    }

    @OnClick({R.id.iv_share,R.id.rl_back, R.id.iv_share_dealer, R.id.iv_share_shop, /*R.id.tv_notice, */R.id.switch_button_layout
            , R.id.view_stay_send, R.id.view_stay_pay, R.id.view_stay_take, R.id.view_stay_sale, R.id.tv_setting,R.id.layout_auto_order})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_auto_order:
                ARouter.getInstance().build(AroutePath.DEALER_SALE_ORDERS_ACTIVITY).withInt("auto_type",1).navigation();
                break;
            case R.id.switch_button_layout:
                if (isSwitchNew){
                    isSwitchNew = false;
                    switchButtonBg.animate().translationX(ScreenUtils.dp2px(firstSwitchNew?46:0)).setInterpolator(new DecelerateInterpolator(2));
                    toolsAdapter.setType(1);
                }else {
                    isSwitchNew = true;
                    switchButtonBg.animate().translationX(ScreenUtils.dp2px(firstSwitchNew?0:-46)).setInterpolator(new DecelerateInterpolator(2));
                    toolsAdapter.setType(0);
                }
                SPUtils.getInstance().put(Config.SHOW_DEALER_BENCH_GRID_NEW, isSwitchNew);
                break;
            case R.id.rl_back:
                Objects.requireNonNull(getActivity()).finish();
                break;
            case R.id.iv_share_dealer:
                CommonUtil.goAnyWhere(mContext, dealerBean.inviteInfo.inviteAgent.redirectUrl, "", "", "", "");
                break;
            case R.id.iv_share:
            case R.id.iv_share_shop:
                share();
                break;
//            case R.id.tv_notice:
//                CommonUtil.goAnyWhere(mContext, dealerBean.noticeAdv.get((Integer) tvNotice.getTag()).redirectUrl,
//                        dealerBean.noticeAdv.get((Integer) tvNotice.getTag()).redirectId, "", "", "");
//                break;
            case R.id.view_stay_send:
                SPUtils.getInstance().put(Config.TIME_DEALER_BENCH_ORDER_SEND,String.valueOf(TimeUtil.get_current_time()));
                ARouter.getInstance().build(AroutePath.DEALER_SALE_ORDERS_ACTIVITY)
                        .withInt("position",2).navigation();
                break;
            case R.id.view_stay_pay:
                ARouter.getInstance().build(AroutePath.DEALER_SALE_ORDERS_ACTIVITY)
                        .withInt("position",1).navigation();
                break;
            case R.id.view_stay_take:
                ARouter.getInstance().build(AroutePath.DEALER_SALE_ORDERS_ACTIVITY)
                        .withInt("position",3).navigation();
                break;
            case R.id.view_stay_sale:
                SPUtils.getInstance().put(Config.TIME_DEALER_BENCH_ORDER_SALE,String.valueOf(TimeUtil.get_current_time()));
                Fragment fragment = (Fragment) ARouter.getInstance().build(AroutePath.AFTER_SALE_SERVE_FRAGMENT)
                        .navigation();
                FragmentHostActivity.openFragment(mContext, fragment);
                break;
            case R.id.tv_setting:
                ARouter.getInstance().build(AroutePath.DEALER_STORE_INFO_ACTIVITY).navigation();
                break;
        }
    }

    private void share(){
        if (dealerBean != null && dealerBean.inviteInfo != null &&
                dealerBean.inviteInfo.shareShop != null && dealerBean.inviteInfo.shareShop.shareInfo != null) {
            DealerBean.InviteInfoBean.ShareShopBean.ShareInfoBean shareInfo = dealerBean.inviteInfo.shareShop.shareInfo;
            ShareCommonDialog shareComDialog = new ShareCommonDialog(Objects.requireNonNull(getActivity()));
            shareComDialog.show();
            shareComDialog.setShareData(shareInfo.shareTitle, shareInfo.shareUrl,
                    shareInfo.shareDesc, shareInfo.shareImg, shareInfo.jumpType
                    , shareInfo.path, "");
            shareComDialog.shareDealerData(shareInfo);
            shareComDialog.setHide_url_friend_circle("1");
            if (SPUtils.getInstance().getInt(Config.SHOW_GUIDE_DEALER_BENCH,-1) == 0){
                shareComDialog.setOnDismissListener( dialog -> {
                    guideIndex = 1;
                    SPUtils.getInstance().put(Config.SHOW_GUIDE_DEALER_BENCH,1);
                    showGuide();
                });
            }
        }
    }

    @Override
    public void showData(DealerBean dataBean) {
        refreshLayout.finishRefresh();
        if (dataBean != null) {
            dealerBean = dataBean;
            //店铺名称
            if (dataBean.shopInfo != null) {
                tvShopTitle.setText(dataBean.shopInfo.name);
                ViewTransformUtil.glideImageView(getActivity(),dataBean.shopInfo.logo,ivShopLogo, new Transformation[]{new CenterCrop(),
                        new RoundedCornersTransformation(ScreenUtils.dp2px(6), 0)}, R.mipmap.defaults);
            }
            //自动单
            if (dataBean.autoOrderInfo != null){
                tvAutoOrder.setText(dataBean.autoOrderInfo.leftTitle);
                tvAutoOrderNum.setText(dataBean.autoOrderInfo.autoOrderNum);
                tvAutoOrderUnit.setText(dataBean.autoOrderInfo.leftSubTitle);
                tvAutoOrderDesc.setText(dataBean.autoOrderInfo.rightTitle);
            }
            //公告信息
//            mHandler.removeMessages(1);
//            newsPosition = 0;
            if (dataBean.noticeAdv != null && dataBean.noticeAdv.size() > 0) {
                tvNotice.setList(dataBean.noticeAdv);
                if (dataBean.noticeAdv.size()>1) {
                    if (!tvNotice.isScroll()){
                        tvNotice.setText(dataBean.noticeAdv.get(0).title);
                        tvNotice.startScroll();
                    }
//                    mHandler.sendEmptyMessage(1);
                }else {
                    tvNotice.setText(dataBean.noticeAdv.get(0).title);
                    if (tvNotice.isScroll()){
                        tvNotice.stopScroll();
                    }
//                    tvNotice.setText(dealerBean.noticeAdv.get(newsPosition).title);
//                    tvNotice.setTag(newsPosition);
                }
                layoutNotice.setVisibility(View.VISIBLE);
            } else {
                layoutNotice.setVisibility(View.GONE);
            }

            //8分格---广告位
            if (dataBean.toolsAdv != null && dataBean.toolsAdv.size() > 0) {
                recyclerTools.setVisibility(View.VISIBLE);
                toolsAdapter.setNewData(dataBean.toolsAdv);
                toolsAdapter.setType(isSwitchNew?0:1);
            } else {
                recyclerTools.setVisibility(View.GONE);
            }

            //待处理相关信息
            if (dataBean.orderSumInfo != null) {

                tvStayPay.setText(dataBean.orderSumInfo.payingOrderSum);
                tvStaySend.setText(dataBean.orderSumInfo.paidOrderSum);

                if (!TextUtils.isEmpty(dataBean.orderSumInfo.paidOrderSum)&& Long.parseLong(dataBean.orderSumInfo
                        .paidOrderSum)>0&&isOrderStatusDay(SPUtils.getInstance().getString(Config.TIME_DEALER_BENCH_ORDER_SEND))){
                    lottieToStaySend.playAnimation();
                    viewToStaySend.setVisibility(View.VISIBLE);
                }else {
                    viewToStaySend.setVisibility(View.INVISIBLE);
                    lottieToStaySend.pauseAnimation();
                }

                tvStayTake.setText(dataBean.orderSumInfo.shippingOrderSum);
                tvStaySale.setText(dataBean.orderSumInfo.afterSaleOrderSum);

                if (!TextUtils.isEmpty(dataBean.orderSumInfo.afterSaleOrderSum)&& Long.parseLong(dataBean
                        .orderSumInfo.afterSaleOrderSum)>0&& viewToStaySend.getVisibility()!=View.VISIBLE
                        &&isOrderStatusDay(SPUtils.getInstance().getString(Config.TIME_DEALER_BENCH_ORDER_SALE))){
                    lottieToStaySale.playAnimation();
                    viewToStaySale.setVisibility(View.VISIBLE);
                }else {
                    viewToStaySale.setVisibility(View.INVISIBLE);
                    lottieToStaySale.pauseAnimation();
                }
            }

            //分享广告位
            if (dataBean.shopInfo != null) {
                if (dataBean.inviteInfo.inviteAgent != null) {
                    ViewTransformUtil.glideImageView(mContext, dataBean.inviteInfo.inviteAgent.imgUrl, ivShareDealer,
                            new RoundedCornersTransformation(ScreenUtils.dp2px(7), 0),
                            R.mipmap.defaults);
                }
                if (dataBean.inviteInfo.shareShop != null) {
                    ViewTransformUtil.glideImageView(mContext, dataBean.inviteInfo.shareShop.imgUrl, ivShareShop,
                            new RoundedCornersTransformation(ScreenUtils.dp2px(7), 0),
                            R.mipmap.defaults);
                }
            }
            viewScroll.setVisibility(View.VISIBLE);

            //新手引导
            if (SPUtils.getInstance().getInt(Config.SHOW_GUIDE_DEALER_BENCH,-1) == -1){
                guideIndex = 0;
                SPUtils.getInstance().put(Config.SHOW_GUIDE_DEALER_BENCH,0);
                showGuide();
            }else if (SPUtils.getInstance().getInt(Config.SHOW_GUIDE_DEALER_BENCH,-1) == 0){
                guideIndex = 1;
                SPUtils.getInstance().put(Config.SHOW_GUIDE_DEALER_BENCH,1);
                showGuide();
            }
        }
    }

    private boolean isOrderStatusDay(String startTime){
        if (TextUtils.isEmpty(startTime)){
            return true;
        }else {
            return 0 != TimeUtil.time_remain_day(startTime, String.valueOf(TimeUtil.get_current_time()));
        }
    }

    private GuideDealerBenchDialog guideDialog;

    private int guideIndex = 0;
    private boolean isListenerDismiss = true;
    private void showGuide(){
        if (guideDialog == null) {
            guideDialog = new GuideDealerBenchDialog(getActivity(), guideIndex, new GuideDealerBenchDialog.ClickImage() {
                @Override
                public void onClickImg(int index) {
                    if (index == 0){
                        isListenerDismiss = false;
                        guideDialog.dismiss();
                        share();
                    }else {
                        guideDialog.dismiss();
                        ARouter.getInstance().build(AroutePath.PURCHASE_ACTIVITY).navigation();
                    }

                }
            });
        }

        if (guideIndex == 1){
            guideDialog.setNextImages();
        }

        guideDialog.setOnDismissListener((dialog) -> {
            if (!isListenerDismiss) {
                isListenerDismiss = true;
                return;
            }
            if (guideIndex == 0){
                guideIndex = 1;
                SPUtils.getInstance().put(Config.SHOW_GUIDE_DEALER_BENCH,1);
                showGuide();
            }
        });
        guideDialog.show();
    }

    @Override
    public void showDataFailed(String msg) {
        ToastUtil.showToast(msg);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (tvNotice != null && tvNotice.isScroll()){
            tvNotice.stopScroll();
        }
//        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
